<?php
// monitor_api.php
header('Content-Type: application/json');

// 配置
$config = [
    'api_key' => 'your_secret_key_here',
    'log_file' => dirname(__FILE__) . '/monitor_logs/monitor_data.json',
    'max_log_size' => 10 * 1024 * 1024, // 10MB
];

// 检查API密钥
if (!isset($_POST['api_key']) || $_POST['api_key'] !== $config['api_key']) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

// 获取POST数据（JSON格式）
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (!$data) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid JSON']);
    exit;
}

// 验证必需字段
$required_fields = ['timestamp', 'type', 'status', 'details', 'severity'];
foreach ($required_fields as $field) {
    if (!isset($data[$field])) {
        http_response_code(400);
        echo json_encode(['error' => "Missing field: $field"]);
        exit;
    }
}

// 确保日志目录存在
$log_dir = dirname($config['log_file']);
if (!is_dir($log_dir)) {
    mkdir($log_dir, 0755, true);
}

// 防止日志文件过大
if (file_exists($config['log_file']) && filesize($config['log_file']) > $config['max_log_size']) {
    $backup_file = $config['log_file'] . '.' . date('Y-m-d-His');
    rename($config['log_file'], $backup_file);
}

// 读取现有数据
$log_data = [];
if (file_exists($config['log_file'])) {
    $existing_data = file_get_contents($config['log_file']);
    $log_data = json_decode($existing_data, true) ?: [];
}

// 添加新记录
$log_data[] = [
    'timestamp' => $data['timestamp'],
    'type' => $data['type'],
    'status' => $data['status'],
    'details' => $data['details'],
    'severity' => $data['severity'],
    'ip' => $_SERVER['REMOTE_ADDR']
];

// 只保留最近1000条记录
if (count($log_data) > 1000) {
    $log_data = array_slice($log_data, -1000);
}

// 保存数据
file_put_contents($config['log_file'], json_encode($log_data, JSON_PRETTY_PRINT));

// 响应成功
echo json_encode(['success' => true, 'message' => 'Data received']);

// 可选：发送告警邮件（针对严重错误）
if ($data['severity'] === 'error') {
    send_alert_email($data);
}

function send_alert_email($data) {
    $to = 'admin@your-domain.com';
    $subject = "监控告警: {$data['type']} - {$data['status']}";
    $message = "
    监控系统检测到问题：
    
    时间: {$data['timestamp']}
    类型: {$data['type']}
    状态: {$data['status']}
    详情: {$data['details']}
    严重程度: {$data['severity']}
    ";
    
    mail($to, $subject, $message);
}
?>


// monitor_dashboard.php
$log_file = dirname(__FILE__) . '/monitor_logs/monitor_data.json';

if (!file_exists($log_file)) {
    die('暂无监控数据');
}

$data = json_decode(file_get_contents($log_file), true);
$recent_data = array_slice($data, -50); // 显示最近50条记录
?>
<!DOCTYPE html>
<html>
<head>
    <title>系统监控面板</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .monitor-item { padding: 10px; margin: 5px 0; border-left: 4px solid; }
        .info { border-color: #2196F3; background: #E3F2FD; }
        .warning { border-color: #FF9800; background: #FFF3E0; }
        .error { border-color: #F44336; background: #FFEBEE; }
        .timestamp { color: #666; font-size: 0.9em; }
        .stats { background: #f5f5f5; padding: 15px; margin: 20px 0; }
    </style>
</head>
<body>
    <h1>系统监控面板</h1>
    
    <?php
    // 统计信息
    $stats = ['info' => 0, 'warning' => 0, 'error' => 0];
    $type_stats = [];
    foreach ($data as $item) {
        $stats[$item['severity']]++;
        $type_stats[$item['type']] = ($type_stats[$item['type']] ?? 0) + 1;
    }
    ?>
    
    <div class="stats">
        <h3>统计概览</h3>
        <p>总记录数: <?= count($data) ?></p>
        <p>信息: <?= $stats['info'] ?> | 警告: <?= $stats['warning'] ?> | 错误: <?= $stats['error'] ?></p>
    </div>
    
    <h3>最近监控记录</h3>
    <?php foreach (array_reverse($recent_data) as $item): ?>
        <div class="monitor-item <?= $item['severity'] ?>">
            <div class="timestamp"><?= $item['timestamp'] ?></div>
            <strong><?= $item['type'] ?></strong>: 
            <?= $item['details'] ?>
            <span style="float: right; font-weight: bold;"><?= strtoupper($item['status']) ?></span>
        </div>
    <?php endforeach; ?>
</body>
</html>
